package com.itheima.search.service.impl;

import com.itheima.search.service.BookIndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 图书索引管理服务实现
 * 
 * @author itheima
 */
@Slf4j
@Service
public class BookIndexServiceImpl implements BookIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    
    private static final String BOOK_INDEX = "book";

    @Override
    public void addBookToIndex(Integer bookId) {
        try {
            log.info("添加图书到ES索引: bookId={}", bookId);
            
            // TODO: 实现从数据库查询图书信息并添加到ES
            // 1. 通过Feign调用book-service获取图书详情
            // 2. 构建IndexRequest
            // 3. 执行索引操作
            
            log.warn("图书索引添加功能待实现: bookId={}", bookId);
            
        } catch (Exception e) {
            log.error("添加图书到ES索引失败: bookId={}", bookId, e);
            throw new RuntimeException("添加图书到ES索引失败", e);
        }
    }

    @Override
    public void updateBookInIndex(Integer bookId) {
        try {
            log.info("更新ES索引中的图书: bookId={}", bookId);
            
            // TODO: 实现图书索引更新
            // 1. 通过Feign调用book-service获取最新图书详情
            // 2. 构建UpdateRequest或先删除后添加
            // 3. 执行更新操作
            
            log.warn("图书索引更新功能待实现: bookId={}", bookId);
            
        } catch (Exception e) {
            log.error("更新ES索引中的图书失败: bookId={}", bookId, e);
            throw new RuntimeException("更新ES索引中的图书失败", e);
        }
    }

    @Override
    public void deleteBookFromIndex(Integer bookId) {
        try {
            log.info("从ES索引中删除图书: bookId={}", bookId);
            
            // 创建删除请求
            DeleteRequest deleteRequest = new DeleteRequest(BOOK_INDEX, bookId.toString());
            
            // 执行删除操作
            DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            
            log.info("图书已从ES索引中删除: bookId={}, result={}", 
                bookId, deleteResponse.getResult());
            
        } catch (Exception e) {
            log.error("从ES索引中删除图书失败: bookId={}", bookId, e);
            throw new RuntimeException("从ES索引中删除图书失败", e);
        }
    }
}

